package org.facyt.commons.view.field;

import java.lang.reflect.ParameterizedType;
import java.util.Collection;

import javax.annotation.PostConstruct;

import org.facyt.commons.view.field.container.SelectItemContainer;

import com.vaadin.ui.ComboBox;

@SuppressWarnings("serial")
public abstract class BaseComboBox<T> extends ComboBox {

	protected String captionNullSelection;
	
	public BaseComboBox() {
		super();
	}

	public BaseComboBox(String captionNullSelection) {
		super();
		this.captionNullSelection = captionNullSelection;
	}

	public BaseComboBox(String caption, String captionNullSelection) {
		super(caption);
		this.captionNullSelection = captionNullSelection;
	}

	@SuppressWarnings("unchecked")
	@PostConstruct
	public final void init() {

		setImmediate(true);	
		Class<? super T> type = (Class<? super T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
		SelectItemContainer<T> items = new SelectItemContainer<T>(type, getCaptionNullSelection());
		items.addAll(getItems());
		setContainerDataSource(items);
		setItemCaptionPropertyId(getItemCaptionProperty());
		setNullSelectionItemId(items.getEmptyValue());

	}

	public String getCaptionNullSelection() {
		return captionNullSelection;
	}
	
	public void setCaptionNullSelection(String captionNullSelection) {
		this.captionNullSelection = captionNullSelection; 
	}

	protected abstract Object getItemCaptionProperty();

	protected abstract Collection<? extends T> getItems();

}
